//
//  HELHomeVC.m
//  HandheldELearn
//
//  Created by wsj2015 on 16/7/11.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELHomeVC.h"
#import "CSStickyHeaderFlowLayout.h"
#import "HELHomeCollectSectiionHeader.h"
#import "HELHomeCell.h"
#import "HELSearchVC.h"
#import "HospitalInCoureseVC.h"
#import "HELFirstHomeCell.h"
#import "HELNavigationContrller.h"
#import "UISearchBar+VDInnerComponents.h"
#import "JCAlertView.h"
#import "HELCourseDetailVC.h"
#import "MJRefresh.h"
#import "WLReloadPromptView.h"
#import "UIViewController+SQExtension.h"
#import "HELNetworkManager.h"
#import "HELDepartmentModel.h"
#import "UIScrollView+WSJRefresh_MJ.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "HELGrowHeader.h"
#import "HELCourseVedioVC.h"
#import "HELVedioAndCourseControllVC.h"

#import "SGScanningQRCodeVC.h"
#import "HELMySignInVC.h"

#import "UINavigationController+WXSTransition.h"
#import "HELMeetingInfo.h"

@interface HELHomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (nonatomic,  strong) UICollectionView *collectView;

@property (nonatomic,  strong) UIView *courseView;

@property (nonatomic,  strong) UISearchBar *searchBar;

@property (nonatomic,  strong) UIView *navCover;

@property (nonatomic,  strong) NSString *bannerImage;







@end

@implementation HELHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    
    
}


- (void)configUI{
    
    UIBarButtonItem *right =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_noti"] style:0 target:self action:@selector(messageNot)];
    self.navigationItem.rightBarButtonItem  =right;
    
    [self.collectView registerNib:[UINib nibWithNibName:@"HELFirstHomeCell" bundle:nil] forCellWithReuseIdentifier:@"HELFirstHomeCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCell" bundle:nil] forCellWithReuseIdentifier:@"HELHomeCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCollectSectiionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HELHomeCollectSectiionHeader"];
    [self.view addSubview:self.collectView];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELGrowHeader" bundle:nil]
       forSupplementaryViewOfKind:CSStickyHeaderParallaxHeader
              withReuseIdentifier:@"HELGrowHeader"];
    UIBarButtonItem *left =[[UIBarButtonItem alloc] initWithImage:nil style:0 target:self action:nil];
    self.navigationItem.leftBarButtonItems =@[left];
    self.navigationItem.titleView = self.searchBar;
    
    UIBarButtonItem *menuBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_camera_7_gray"] style:UIBarButtonItemStyleDone target:self action:@selector(menuAction)];
    self.navigationItem.leftBarButtonItem = menuBtn;
    defineWeakSelf;
//    [self refreshViewWithScrollView:self.collectView refreshBlock:^{
//        [weakSelf requestData];
//    }];
    
   [self.collectView wsj_HeaderRefreshBlock:^{
        [weakSelf requestData];
   }];
  
//    [self.collectView addLegendHeaderWithRefreshingBlock:^{
//        
//    }];
   
//    [self.collectView addLegendHeaderWithRefreshingBlock:^{
//      
//
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.collectView.header endRefreshing];
////            []
////            [self.view bringSubviewToFront:self.noNetView];
//          
//        });
//    }];
    
 
    
    
}

#pragma mark -二维码扫描
-(void)menuAction{
    
//    [self.navigationController wxs_pushViewController:[HELSignInVC new] animationType:WXSTransitionAnimationTypeBrickOpenVertical];
  
    
    SGScanningQRCodeVC *scan =[[SGScanningQRCodeVC alloc] init];
    
    weakSelf_define;
    scan.callback  =^(NSString *qrcode){
        
        HELMySignInVC *vc = [HELMySignInVC new];
        vc.courseId = qrcode;
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
//        [weakSelf.navigationController wxs_pushViewController:[HELMySignInVC new] makeTransition:^(WXSTransitionProperty *transition) {
//            transition.animationType = WXSTransitionAnimationTypeBrickOpenVertical;
//            transition.isSysBackAnimation = NO;
//            transition.backGestureType = 0;
//        }];
//    
    };
    HELNavigationContrller *nav = [[HELNavigationContrller alloc] initWithRootViewController:scan];
    
    [self wxs_presentViewController:nav animationType:WXSTransitionAnimationTypeSysCubeFromLeft completion:nil];

    
    

}


#pragma mark -请求数据...
- (void)requestData{
  
  defineWeakSelf;
   
    NSString *hospitalId = [HELAppManager userInfo].hospitalId;
    if (!hospitalId) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"该用户不属于任何医院..." ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:nil];
        return;
    }
    [[HELNetworkManager sharedMg] GET:kHomeData_url parameters:@{@"hospitalId":[HELAppManager userInfo].hospitalId} success:^(NSDictionary *responseObject) {
     
      [weakSelf.dataArray removeAllObjects];
        
        if (responseObject[@"bannerImage"]) {
            weakSelf.bannerImage = responseObject[@"bannerImage"];
        }
        
      if ([responseObject[@"departments"] isKindOfClass:[NSArray class]]) {
        weakSelf.dataArray = [HELDepartmentModel mj_objectArrayWithKeyValuesArray:responseObject[@"departments"]];
      }
       [weakSelf.collectView.header endRefreshing];
       [weakSelf.collectView reloadData];
  } failure:^(NSString *err) {
      [weakSelf.collectView.header endRefreshing];
  }];
    
}


- (void)messageNot{
    HELMeetingInfo *meetingInfoVC = [HELMeetingInfo new];
    meetingInfoVC.title = @"会议信息";
    [self.navigationController pushViewController:meetingInfoVC animated:YES];
 
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //self.noNeedChangeNavbar = NO;
    [[HELAppManager sharedAppManger].appNav firstNav];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"personVCUPoffset"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
     [self.searchBar endEditing:YES];
//    self.noNeedChangeNavbar =YES;
}



#pragma mark -当行覆盖视图
- (UIView *)navCover{
    if (!_navCover) {
        _navCover = [UIView new];
        _navCover.backgroundColor  = HexRGB_WSJ(252, 79, 72);
        _navCover.frame = CGRectMake(0, 0, kScreenWidth, 64);
        [self.navigationController.navigationBar addSubview:_navCover];
        
    }
    return _navCover;
}

- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar =[[UISearchBar alloc] init];
        _searchBar.frame = CGRectMake(0, 0, kScreenWidth- 100, 33);
        _searchBar.placeholder = @"搜索平台资料";
        _searchBar.delegate = self;
        _searchBar.translucent = YES;
        _searchBar.searchBarStyle = UIBarStyleBlackTranslucent;
        _searchBar.tintColor = [UIColor whiteColor];
        
        UITextField *tf =[_searchBar vd_inputTextField];
        tf.layer.borderWidth = 1;
        tf.layer.borderColor = [UIColor whiteColor].CGColor;
        tf.textColor = [UIColor whiteColor];
        tf.layer.cornerRadius = 14;
        tf.layer.masksToBounds = YES;
        tf.textColor =[UIColor whiteColor];
        [tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
        
    }
    return _searchBar;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    HELSearchVC *vc =[HELSearchVC new];
    [self.navigationController pushViewController:vc animated:YES];

    return NO;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.searchBar endEditing:YES];
}
- (UIView *)courseView{
    if (!_courseView) {
        _courseView = [[UIView alloc] init];
    }
    return _courseView;
}
- (UICollectionView *)collectView{
    if (!_collectView) {
      
       CSStickyHeaderFlowLayout *layout =[[CSStickyHeaderFlowLayout alloc]init];

        
//        if ([layout isKindOfClass:[CSStickyHeaderFlowLayout class]]) {
            layout.parallaxHeaderReferenceSize = CGSizeMake(self.view.frame.size.width, kScreenWidth *.544);
        layout.parallaxHeaderMinimumReferenceSize = CGSizeMake(kScreenWidth, kScreenWidth *.544);
            layout.itemSize = CGSizeMake(self.view.frame.size.width, layout.itemSize.height);
            // If we want to disable the sticky header effect
            layout.disableStickyHeaders = NO;
//        }


        CGFloat space = 8;
   
        layout.sectionInset =UIEdgeInsetsMake(4, space, 2, space );
        layout.minimumInteritemSpacing = 4;
        layout.minimumLineSpacing = 6;
        CGRect frame =CGRectMake(0, -64, kScreenWidth, kScreenHeight +15);
        _collectView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.alwaysBounceVertical =YES;
        _collectView.backgroundColor = kAppBg;
        if ([_collectView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
            _collectView.prefetchingEnabled = NO;
        }
//
      

    }
    return _collectView;
   
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    HospitalInCoureseVC *vc =[HospitalInCoureseVC new];
//    [self.navigationController pushViewController:vc animated:YES];
      HELCourseDetailVC *vc = [HELCourseDetailVC new];
    HELDepartmentModel *department = self.dataArray[indexPath.section -1];
    HELStudyDataModel *model =department.studyDataArray[indexPath.row];
    vc.courseId = [model.id integerValue];
     [self.navigationController pushViewController:vc animated:YES];
  
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0 ) {
        return CGSizeMake(kScreenWidth -4, 104.5);
    }else{
        
        //适配屏幕
        CGFloat w = (kScreenWidth -24)/3;
        CGFloat h =120;

        if (kScreenWidth == 320 && kScreenHeight ==480) {//iphone4
             h =120;
        }else if(kScreenWidth == 320 && kScreenHeight ==568){ //iphone 5
             h =120;
        }else if(kScreenWidth == 375 && kScreenHeight == 667){ //iphone 6
             h =126;
        }else if(kScreenWidth == 414 && kScreenHeight == 736){ //iphone 6P
             h =136;
        }
        
        return CGSizeMake(w, h);
    }
    
    
}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//
//
//
//}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section ==0) {
        return  CGSizeZero;
    }
    
    return CGSizeMake(kScreenWidth, 33);
   
}
#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    return [self.dataArray count];
    return self.dataArray.count+1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (section == 0) {
        return 1;
    }
    HELDepartmentModel *model =self.dataArray[section-1];
    return model.studyDataArray.count;
   
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    weakSelf_define;
//    NSDictionary *obj = self.dataArray[indexPath.section];
    if (indexPath.section ==0) {
        HELFirstHomeCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"HELFirstHomeCell"
                                                                          forIndexPath:indexPath];
        cell.clickBlock = ^(NSInteger index){
            [weakSelf goIntoCourseVC:index indexPath:indexPath];
        };
        return cell;
    }
    
    HELHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HELHomeCell"
                                                             forIndexPath:indexPath];
//
//    cell.textLabel.text = [[obj allValues] firstObject];
    HELDepartmentModel *model =self.dataArray[indexPath.section -1];
    HELStudyDataModel *sduty =model.studyDataArray[indexPath.row];
    cell.model = sduty;
    
    return cell;
}
#pragma mark -进入课程

- (void)goIntoCourseVC:(NSInteger)courseType indexPath:(NSIndexPath *)indexPath{
    
    
    //院内课程
    if (courseType == 0) {
        HELSearchVC *vc= [HELSearchVC new];
        vc.HELSearchVCType = HELSearchVCCouresType_hospitalIn;
       
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    //公开课程 学会课程
   
    if (courseType ==1) {
        [self.navigationController pushViewController:[HELVedioAndCourseControllVC new] animated:YES];
    }
    
    if (courseType == 2) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"本功能暂未开放~" ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:nil];
        return;
    }
    
    // 点击more的时候
    if (courseType == -1) {
        HELSearchVC *vc= [HELSearchVC new];
        vc.departmentModel = self.dataArray[indexPath.section-1];
        [self.navigationController pushViewController:vc animated:YES];
    }
   
}


//cell的最小行间距
//
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    
//    return 4;
//
//}
//
//
//
////cell的最小列间距
//
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 8;
//}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
//        NSDictionary *obj = self.dataArray[indexPath.section];
        
        HELHomeCollectSectiionHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                   withReuseIdentifier:@"HELHomeCollectSectiionHeader"
                                                                          forIndexPath:indexPath];
        HELDepartmentModel *model =self.dataArray[indexPath.section-1];
        cell.titleL.text =model.departmentName;
        
        defineWeakSelf;
        cell.getMoreBlock = ^(){
            [weakSelf goIntoCourseVC:-1 indexPath:indexPath];
          
        };
        
        return cell;
    } else if ([kind isEqualToString:CSStickyHeaderParallaxHeader]) {
        HELGrowHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                            withReuseIdentifier:@"HELGrowHeader"
                                                                                   forIndexPath:indexPath];

        if (self.bannerImage) {
           
            [cell.headerPic setImageWithURL:[NSURL URLWithString:self.bannerImage] placeholderImage:[UIImage imageNamed:@"暂无图片.jpg"]usingActivityIndicatorStyle:1];
        }
     
        return cell;
    }
    return nil;
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    if (self.noNeedChangeNavbar ==YES) {
//        return;
//    }
//    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
//    [self navigationBarGradualChangeWithScrollView:scrollView titleView:nil movableView:nil offset:100 color:kMainColor];
//}

@end
